package com.graph.similar;

import com.graph.base.VertexInterface;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiWu
 * 2018-1-16
 */
public class CosineSimilarAlgorithm {

    /**
     *
     * @Title: cosSimilarity
     * @Description: 得到两个节点的相似性
     * @param @param vertexInterface1
     * @param @param vertexInterface2
     * @param @return
     * @return Double
     * @throws
     */
    public static Double cosSimilarity(VertexInterface vertexInterface1, VertexInterface vertexInterface2){
        try{
            Map<String, Integer> firstTfMap = null;
            Map<String, Integer> secondTfMap = null;
            if(firstTfMap.size() < secondTfMap.size()){
                Map<String, Integer> temp = firstTfMap;
                firstTfMap = secondTfMap;
                secondTfMap = temp;
            }
            return calculateCos((LinkedHashMap<String, Integer>)firstTfMap, (LinkedHashMap<String, Integer>)secondTfMap);
        }catch(Exception e){
            e.printStackTrace();
        }
        return 0d;
    }

    /**
     *
     * @Title: calculateCos
     * @Description: 计算余弦相似性
     * @param @param first
     * @param @param second
     * @param @return
     * @return Double
     * @throws
     */
    private static Double calculateCos(LinkedHashMap<String, Integer> first,LinkedHashMap<String, Integer> second){

        List<Map.Entry<String, Integer>> firstList = new ArrayList<Map.Entry<String, Integer>>(first.entrySet());
        List<Map.Entry<String, Integer>> secondList = new ArrayList<Map.Entry<String, Integer>>(second.entrySet());
        //计算相似度
        double vectorFirstModulo = 0.00;//向量1的模
        double vectorSecondModulo = 0.00;//向量2的模
        double vectorProduct = 0.00; //向量积
        int secondSize = second.size();
        for(int i = 0;i < firstList.size();i ++){
            if(i < secondSize){
                vectorSecondModulo += secondList.get(i).getValue().doubleValue()*secondList.get(i).getValue().doubleValue();
                vectorProduct += firstList.get(i).getValue().doubleValue()*secondList.get(i).getValue().doubleValue();
            }
            vectorFirstModulo += firstList.get(i).getValue().doubleValue()*firstList.get(i).getValue().doubleValue();
        }
        return vectorProduct / (Math.sqrt(vectorFirstModulo) * Math.sqrt(vectorSecondModulo));
    }

    public static void main(String[] args){
    }
}
